/*
自定义中间件
 */
import 'package:shelf/shelf.dart';
import 'package:shelf_multipart/multipart.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_log.dart';

abstract class XCustomMiddlewareUtils {

  //自定义中间件
  static Middleware getCustomMiddleware(){
    return (Handler innerHandler) {
      return (Request request) async {
        // 在处理请求之前执行操作

        //Map<String, String> requestHeaders=request.headers;
        //验证headers,token等...
        //return Response.unauthorized(null);

        // XLogUtils.printLog('----XShelf Middleware: Request,protocolVersion: ${request.protocolVersion}');
        // XLogUtils.printLog('----XShelf Middleware: Request,contentLength: ${request.contentLength}');

        Response response;

        if(request.isMultipart){
          XLogUtils.printLog('---XShelf Middleware: Request,method=${request.method}, url=/${request.url}, isMultipart=${request.isMultipart}');
          response = await innerHandler(request);
        }else{
          /*
        注意:如果在这里读取requestBody = await request.readAsString(),则后面的innerHandler无法再次request.readAsString(),
        因此要重新创建一个request: request.change(body:requestBody)
         */

          String requestBody = await request.readAsString();
          Request newRequest=request.change(body:requestBody);
          XLogUtils.printLog('---XShelf Middleware: Request,method=${request.method}, url=/${request.url}, isMultipart=${request.isMultipart}, requestBody=$requestBody');

          // 继续处理请求
          response = await innerHandler(newRequest);

        }

        // 在处理请求之后执行操作
        //print('Custom Middleware: Request handled. Response status: ${response.statusCode}');

        return response;
      };
    };
  }

}